package com.atguigu.common.config.exception;

import com.atguigu.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * ClassName GlobalExceptionHandler
 * Package: com.atguigu.common.config.exception
 * ProjectName guigu-oa-parent
 * Description:
 *
 * @Author: 比特张
 * @Create: 2023/4/18 - 15:42
 * @Version: v1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常处理，执行的方法。
     *
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result error(Exception e) {
        return Result.fail().message("[全局异常处理]");
    }

    @ExceptionHandler(DataAccessException.class)
    public Result error(SQLIntegrityConstraintViolationException e) {
        log.error("《新增用户异常现象》:" + e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            String[] split = e.getMessage().split(" ");
            String repeatedName = split[2];
            repeatedName = repeatedName.substring(1, repeatedName.length() - 1);
            log.info("重复用户名称：" + repeatedName);
            return Result.fail().message(repeatedName + "已存在");
        }
        return Result.fail().message("[未知错误]");
    }

    @ExceptionHandler(ArithmeticException.class)
    public Result error(ArithmeticException e) {
        e.printStackTrace();
        return Result.fail().message("执行特定异常处理...");
    }

    @ExceptionHandler(GuiguException.class)
    public Result error(GuiguException e) {
        e.printStackTrace();
        return Result.fail().code(e.getCode()).message(e.getMessage());
    }

    /**
     * spring security异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public Result error(AccessDeniedException e) throws AccessDeniedException {
        return Result.fail().code(205).message("没有操作权限");
    }
}
